package com.ndp.fb.rdb.mongo.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.*;
import com.ndp.fb.constant.MongoConstants;
import com.ndp.fb.mongo.api.AppRetentionMongoService;
import com.ndp.fb.mongo.model.AppRetention;
import com.ndp.fb.util.DateUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * app留存服务
 * Created by jacky.cheng on 2015/10/9.
 */
@Service
public class AppRetentionMongoServiceImpl extends BaseMongoServiceImpl implements AppRetentionMongoService {

    @Override
    public AppRetention findOne(Date day, String appId, String type) {
        day = DateUtil.getUtcDayZero(day);
        DBCollection dbCollection = mongoDBClient.getCollection(getTableName());
        DBObject match = new BasicDBObject();
        match.put("Day", day);
        match.put("AppId", appId);
//        match.put("Type", type); todo test
        DBCursor cursor = dbCollection.find(match).addOption(Bytes.QUERYOPTION_NOTIMEOUT);
        while (cursor.hasNext()) {
            return JSONObject.parseObject(JSON.toJSONString(cursor.next()), AppRetention.class);
        }
        return null;
    }

    @Override
    public List<AppRetention> findPre7Day(Date day, String appId, String type) {
        day = DateUtil.getUtcDayZero(day);
        DBCollection dbCollection = mongoDBClient.getCollection(getTableName());
        DBObject match = new BasicDBObject();
        DBObject dayObject = new BasicDBObject();
        dayObject.put("$gte", DateUtil.addDateByTypeAndOffset(day, Calendar.DATE, -7));
        dayObject.put("$lte", day);
        match.put("Day", dayObject);
        match.put("AppId", appId);
//        match.put("Type", type); todo test
        DBCursor cursor = dbCollection.find(match).addOption(Bytes.QUERYOPTION_NOTIMEOUT);
        List<AppRetention> result = new ArrayList<>();
        while (cursor.hasNext()) {
            result.add(JSONObject.parseObject(JSON.toJSONString(cursor.next()), AppRetention.class));
        }
        return result;
    }

    @Override
    public String getTableName() {
        return MongoConstants.TABLE_NAME_APP_RETENTION;
    }
}
